﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ThridGroup.ERP.DTO;
using ThridGroup.ERP.DTO.WarehouseManagement;
using ThridGroup.ERP.ProductionSystem;
using ThridGroup.ERP.WarehouseManagement;
using ThridGroup.ERP.Web.Areas.WarehouseManagement.Controllers;
using Microsoft.EntityFrameworkCore;

namespace ThridGroup.ERP.Web.Controllers.WarehouseManagement
{

    /// <summary>
    /// 销售退货控制器
    /// </summary>
    [Route("SalesReturns")]
    public class SalesReturnsController : Controller
    {
        /// <summary>
        /// 销售退货服务
        /// </summary>
        private readonly ISalesReturnsServices _salesReturnsServices;
        /// <summary>
        /// 客户服务
        /// </summary>
        private readonly ICustomerServices _customerServices;
        /// <summary>
        /// 仓库设置服务
        /// </summary>
        private readonly IWarehouseSettingService _warehouseSettingService;
        /// <summary>
        /// 日志记录器
        /// </summary>
        private readonly ILogger<SalesReturnsController> _logger;
      

        /// <summary>
        /// 构造函数，注入所需服务
        /// </summary>
        public SalesReturnsController(ISalesReturnsServices salesReturnsServices, ICustomerServices customerServices , IWarehouseSettingService warehouseSettingService, ILogger<SalesReturnsController> logger) 
        {
            _salesReturnsServices = salesReturnsServices;
            _customerServices = customerServices;
            _warehouseSettingService = warehouseSettingService;
            _logger = logger;
           
        }

        /// <summary>
        /// 销售退货首页视图
        /// </summary>
          [HttpGet("SalesReturnsView")]
        public IActionResult SalesReturnsView()
        {
            return View();
        }
        /// <summary>
        /// 添加销售退货
        /// </summary>
        [HttpPost]
        [Route("AddSalesReturns")]
        [ValidateAntiForgeryToken]
        public async Task<JsonResult> AddSalesReturns(CreSalesReturnsDto dto)
        {
            if (!ModelState.IsValid)
                return Json(new { code = 1, msg = "参数错误", errors = ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage) });
            try
            {
                var id = await _salesReturnsServices.AddSalesReturns(dto);
                return Json(new { code = 0, msg = "添加成功", id });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = "添加失败：" + ex.Message });
            }
        }




        /// <summary>
        /// 客户管理列表，支持分页和按名称筛选
        /// </summary>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">每页数量</param>
        /// <param name="customerName">客户名称</param>
        /// <returns>客户列表</returns>
        [HttpGet]
        [Route("ShowCustomer")]
        public async Task<JsonResult> ShowCustomer(int pageIndex = 1, int pageSize = 10, string? customerName = "")
        {
            var list = await _customerServices.ShowCustomer(pageIndex, pageSize, customerName);
            var result = list.OrderByDescending(m => m.Id).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            return Json(new
            {
                code = 0,
                msg = "",
                count = list.Count,
                data = result

            });
        }



        /// <summary>
        /// 获取仓库设置列表，支持分页和条件筛选
        /// </summary>
        /// <param name="depotCode">仓库编码</param>
        /// <param name="depotName">仓库名称</param>
        /// <param name="location">库位</param>
        /// <param name="page">页码</param>
        /// <param name="limit">每页数量</param>
        /// <returns>仓库设置列表</returns>
        [HttpGet]
        [Route("GetWarehouseSettings")]
        public async Task<IActionResult> GetWarehouseSettings(string depotCode = null, string depotName = null, string location = null, int page = 1, int limit = 10)
        {
            try
            {
                _logger.LogInformation($"开始获取仓库设置列表, 页码: {page}, 每页数量: {limit}, 筛选条件: depotCode={depotCode}, depotName={depotName}, location={location}");

                // 从服务层获取分页数据
                var (data, total) = await _warehouseSettingService.GetWarehouseSettingsPaged(depotCode, depotName, location, page, limit);

                _logger.LogInformation($"获取仓库设置列表成功，总数：{total}, 当前页数据：{data?.Count ?? 0}条");

                return Json(new { code = 0, msg = "获取成功", count = total, data = data });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取仓库设置列表失败");
                return Json(new { code = 1, msg = "获取数据失败：" + ex.Message, count = 0, data = new List<WarehouseSettingDto>() });
            }
        }

        /// <summary>
        /// 分页查询销售退货单，支持多条件筛选
        /// </summary>
        /// <param name="returnNumber">退货单编号（模糊查询）</param>
        /// <param name="salesOrdersCode">销售订单编号（模糊查询）</param>
        /// <param name="customerName">客户名称（模糊查询）</param>
        /// <param name="returnsWarehouse">仓库名称（模糊查询）</param>
        /// <param name="documentStatus">单据状态（等值查询）</param>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">每页数量</param>
        /// <returns>退货单列表及总数</returns>
        [HttpGet]
        [Route("GetSalesReturnsPaged")]
        public async Task<IActionResult> GetSalesReturnsPaged(string returnNumber = null, string salesOrdersCode = null, string customerName = null, string returnsWarehouse = null, int? documentStatus = null, int pageIndex = 1, int pageSize = 10)
        {
            try
            {
                var (data, total) = await _salesReturnsServices.GetSalesReturnsPaged(returnNumber, salesOrdersCode, customerName, returnsWarehouse, documentStatus, pageIndex, pageSize);
                return Json(new { code = 0, msg = "获取成功", count = total, data });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取销售退货单分页数据失败");
                return Json(new { code = 1, msg = "获取数据失败：" + ex.Message, count = 0, data = new List<SalesReturnsListDto>() });
            }
        }


        /// <summary>
        /// 检查退货单编号是否存在
        /// </summary>
        [HttpGet("CheckReturnNumberExists")]
        public async Task<IActionResult> CheckReturnNumberExists(string returnNumber)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(returnNumber))
                {
                    return Json(new { code = 1, msg = "退货单编号不能为空" });
                }

                var result = await _salesReturnsServices.GetSalesReturnsPaged(returnNumber, null, null, null, null, 1, 1);
                bool exists = result.data.Count > 0;
                return Json(new { code = 0, exists });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = "检查退货单编号失败: " + ex.Message });
            }
        }
            
        /// <summary>
        /// 生成退货单编号
        /// </summary>
        [HttpGet("GetNewReturnNumber")]
        public async Task<JsonResult> GetNewReturnNumber()
        {
            
            try
            {
                // 生成格式：GD + 年月日 + 4位随机数
                var today = DateTime.Now;
                string returnNumber = "GD" + today.ToString("yyyyMMdd") + new Random().Next(1000, 9999).ToString();

                return Json(new { code = 0, returnNumber = returnNumber });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = "生成生产工单编号失败：" + ex.Message });
            }
        }

        /// <summary>
        /// 删除单个退货单
        /// </summary>
        [HttpPost("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Delete(int id)
        {
            try
            {
                await _salesReturnsServices.DeleteAsync(id);
                return Json(new { code = 0, msg = "删除成功" });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = "删除失败: " + ex.Message });
            }
        }

        /// <summary>
        /// 批量删除退货单
        /// </summary>
        [HttpPost("BatchDelete")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> BatchDelete([FromForm] List<int> ids)
        {
            try
            {
                await _salesReturnsServices.BatchDeleteAsync(ids);
                return Json(new { code = 0, msg = "批量删除成功" });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = "批量删除失败: " + ex.Message });
            }
        }

        /// <summary>
        /// 根据ID获取退货单详情（反填）
        /// </summary>
        [HttpGet("GetById")]
        public async Task<IActionResult> GetById(int id)
        {
            try
            {
                var dto = await _salesReturnsServices.GetByIdAsync(id);
                return Json(new { code = 0, data = dto });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = "获取详情失败: " + ex.Message });
            }
        }

        /// <summary>
        /// 修改退货单
        /// </summary>
        [HttpPost("Update")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Update(CreSalesReturnsDto dto)
        {
            try
            {
                await _salesReturnsServices.UpdateAsync(dto);
                return Json(new { code = 0, msg = "修改成功" });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = "修改失败: " + ex.Message });
            }
        }

        /// <summary>
        /// 修改退货单状态（草稿改为完成）
        /// </summary>
        [HttpPost("UpdateStatus")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> UpdateStatus(int id, int newStatus)
        {
            try
            {
                await _salesReturnsServices.UpdateStatusAsync(id, newStatus);
                return Json(new { code = 0, msg = "状态修改成功" });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = "状态修改失败: " + ex.Message });
            }
        }

    }
}
